﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace LdCms.Web.Controllers.API.Member.V1
{
    using LdCms.Common.Utility;
    using LdCms.Common.Extension;
    using LdCms.EF.DbModels;
    using LdCms.Common.Security;

    /// <summary>
    /// 会员资料接口
    ///     1、获取会员资料
    ///        GET：member/info/get?access_token=access_token
    ///     2、修改会员资料
    ///        URL：member/info/update?access_token=access_token
    ///        POST：{"company_name":"","name":"","nickname":"","head_image_url":"","sex":0,"phone":"18012345678","email":"","address":"","remark":""}
    ///     3、修改密码
    ///        URL：member/password/update?access_token=access_token
    ///        POST：{"password":"123456"}
    ///     4、重置密码
    ///        URL：member/password/reset?access_token=access_token
    ///        POST：{"sms_pid":"","send_id":"","code":"123456","phone":"18666376363","password":"123456"}
    ///     5、修改手机号码
    ///        URL：member/phone/update?access_token=access_token
    ///        POST：{"sms_pid":"","send_id":"","code":"123456","phone":"123456"}
    /// 
    /// </summary>
    public partial class MemberController : BaseApiController
    {
        /// <summary>
        /// 获取会员资料
        /// </summary>
        /// <param name="access_token"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("info/get")]
        public IActionResult GetMember(string access_token)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(access_token);
                var entity = MemberAccount;
                var data = new
                {
                    memberid = entity.MemberID,
                    rank_id = entity.RankID,
                    rank_name = entity.RankName,
                    user_name = entity.UserName,
                    company_name = entity.CompanyName.IIF(),
                    name = entity.Name.IIF(),
                    nickname = entity.NickName.IIF(),
                    head_image_url = entity.HeadImageUrl.IIF(),
                    sex = entity.Sex.ToInt(),
                    phone = entity.Phone,
                    email = entity.Email.IIF(),
                    address = entity.Address.IIF(),
                    total_points = entity.TotalPoints.ToInt(),
                    total_consumption = entity.TotalConsumption.ToDecimal(),
                    total_amount = entity.TotalAmount.ToDecimal(),
                    remark = entity.Remark.IIF(),
                };
                return Success(logId, "ok", data);
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="formValue">{"company_name":"","name":"","nickname":"","head_image_url":"","sex":0,"phone":"18012345678","email":"","address":"","remark":""}</param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("info/update")]
        public IActionResult UpdateMember(string access_token, [FromBody]JObject formValue)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(access_token);
                var entity = GetMemberAccount(MemberAccount, formValue);
                bool result = AccountService.UpdateAccount(entity);
                if (result)
                    return Success(logId, "ok");
                else
                    return Error(logId, "fail");
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="formValue">{"password":"123456"}</param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("password/update")]
        public IActionResult UpdatePassword(string access_token, [FromBody]JObject formValue)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(access_token);
                bool verifyParams = IsUpdatePasswordParams(formValue);
                string password = GetJObjectValue(formValue, "password");
                string companyId = MemberAccount.CompanyID;
                string memberId = MemberAccount.MemberID;
                var result = AccountService.UpdateAccountPasswordPro(SystemID, companyId, memberId, AlgorithmHelper.MD5(password));
                if (result)
                    return Success(logId, "ok");
                else
                    return Error(logId, "fail");
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="uuid"></param>
        /// <param name="formValue">{"sms_pid":"","send_id":"","code":"123456","phone":"18666376363","password":"123456"}</param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("password/reset")]
        public IActionResult ResetPassword(string uuid, [FromBody]JObject formValue)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(uuid);
                bool verifyParams = IsResetPasswordParams(formValue);
                string phone = GetJObjectValue(formValue, "phone");
                string password = GetJObjectValue(formValue, "password");
                var memberAccount = AccountService.GetAccountByPhone(SystemID, InterfaceAccount.CompanyID, phone);
                string companyId = memberAccount.CompanyID;
                string memberId = memberAccount.MemberID;
                var result = AccountService.UpdateAccountPasswordPro(SystemID, companyId, memberId, AlgorithmHelper.MD5(password));
                if (result)
                    return Success(logId, "ok");
                else
                    return Error(logId, "fail");
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="formValue">{"sms_pid":"","send_id":"","code":"123456","phone":"123456"}</param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("phone/update")]
        public IActionResult UpdatePhone(string access_token, [FromBody]JObject formValue)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(access_token);
                bool verifyParams = IsUpdatePhoneParams(formValue);
                string phone = GetJObjectValue(formValue, "phone");
                if (!Utility.IsMobilePhone(phone)) { return Error(logId, "手机号码格式有误！"); }

                string companyId = MemberAccount.CompanyID;
                string memberId = MemberAccount.MemberID;
                var result = AccountService.UpdateAccountPhonePro(SystemID, companyId, memberId, phone);
                if (result)
                    return Success(logId, "ok");
                else
                    return Error(logId, "fail");
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }


        #region 私有方法
        private Ld_Member_Account GetMemberAccount(Ld_Member_Account memberAccount, JObject formValue)
        {
            try
            {
                int systemId = SystemID;
                string companyName = GetJObjectValue(formValue, "company_name");
                string name = GetJObjectValue(formValue, "name");
                string nickname = GetJObjectValue(formValue, "nickname");
                string headImageUrl = GetJObjectValue(formValue, "head_image_url");
                string sex = GetJObjectValue(formValue, "sex");
                string phone = GetJObjectValue(formValue, "phone");
                string email = GetJObjectValue(formValue, "email");
                string address = GetJObjectValue(formValue, "address");
                string remark = GetJObjectValue(formValue, "remark");
                memberAccount.CompanyName = companyName;
                memberAccount.Name = name;
                memberAccount.NickName = nickname;
                memberAccount.HeadImageUrl = headImageUrl;
                memberAccount.Sex = sex.ToByte();
                memberAccount.Phone = phone;
                memberAccount.Email = email;
                memberAccount.Address = address;
                memberAccount.Remark = remark;
                return memberAccount;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private bool IsUpdatePasswordParams(JObject formValue)
        {
            try
            {
                if (formValue == null)
                    throw new Exception("params not empty！");
                if (formValue.Property("password") == null)
                    throw new Exception("lack password params！");
                if (string.IsNullOrWhiteSpace(GetJObjectValue(formValue, "password")))
                    throw new Exception("password not empty！");
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private bool IsResetPasswordParams(JObject formValue)
        {
            try
            {
                if (formValue == null)
                    throw new Exception("params not empty！");
                if (formValue.Property("phone") == null)
                    throw new Exception("lack phone params！");
                if (formValue.Property("password") == null)
                    throw new Exception("lack password params！");
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private bool IsUpdatePhoneParams(JObject formValue)
        {
            try
            {
                if (formValue == null)
                    throw new Exception("params not empty！");
                if (formValue.Property("phone") == null)
                    throw new Exception("lack phone params！");
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion



    }
}